<?php

/*
=====================================================
 FluxBB - Delux Board Converstations (DBC)
-----------------------------------------------------
 http://dbc-forum.com/
 http://fluxbb.org/
-----------------------------------------------------
 Copyright (c) 2010,2011 FluxBB - Delux Board Conversations (DBC)
-----------------------------------------------------
 Предсловие: Данный скрипт (DBC) не является работой с нуля, то 
 есть ядром скрипта всё также остаётся FuxBB,но теперь в оболочке
 DBC.
=====================================================
*/

define('DBC_PMS_NEW', 1);

define('DBC_ROOT', './');
define('DBC_PM', 1);
require DBC_ROOT.'engine/common.php';
require DBC_ROOT.'engine/modules/pms_new/common_pmsn.php';

if ($DBC_user['g_read_board'] == '0')
	message($lang_common['No view']);

// гостям нельзя
if ($DBC_user['is_guest'])
	redirect('login.php', $lang_common['Redirecting']);

// если выключена совсем или выключена группа и нет новых сообщений
if ($DBC_config['o_pms_enabled'] != '1' || ($DBC_user['g_pm'] == 0 && $DBC_user['messages_new'] == 0))
	message($lang_common['No permission']);

// если была отправка формы
if (isset($_POST['csrf_hash']) || isset($_GET['csrf_hash']))
{
	confirm_referrer('pmsnew.php');
	define('DBC_PMS_NEW_CONFIRM', 1);
}

$action = isset($_REQUEST['action']) ? trim($_REQUEST['action']) : '';
if ($action == 'onoff')
{
	if ($DBC_user['messages_enable'] == 0 || ($DBC_user['messages_enable'] == 1 && isset($_POST['action2']) && defined('DBC_PMS_NEW_CONFIRM')))
	{
		// удаляем сообщения пользователя
		if ($DBC_user['messages_enable'] == 1)
			pmsn_user_delete($DBC_user['id'], 2);
			
		$DBC_user['messages_enable'] = ($DBC_user['messages_enable'] == 0) ? 1 : 0;
		$db->query('UPDATE '.$db->prefix.'users SET messages_enable='.$DBC_user['messages_enable'].' WHERE id='.$DBC_user['id']) or error('Unable to update users table', __FILE__, __LINE__, $db->error());

		redirect('pmsnew.php', $lang_pmsn['Options redirect']);
	}
	else if ($DBC_user['messages_enable'] == 1 && isset($_POST['action2']))
		message($lang_common['Bad referrer']);
	else
		$pmsn_modul = 'closeq';
}
else if ($action == 'email')
{
	if ($DBC_user['messages_email'] == 1)
	{
		$action = $lang_pmsn['Email off Red'];
		$db->query('UPDATE '.$db->prefix.'users SET messages_email=0 WHERE id='.$DBC_user['id']) or error('Unable to update users table', __FILE__, __LINE__, $db->error());
	}
	else
	{
		$action = $lang_pmsn['Email on Red'];
		$db->query('UPDATE '.$db->prefix.'users SET messages_email=1 WHERE id='.$DBC_user['id']) or error('Unable to update users table', __FILE__, __LINE__, $db->error());
	}

	redirect('pmsnew.php', $action);
}
else if ($DBC_user['messages_enable'] == 0 && $DBC_user['messages_new'] == 0) // вдруг сообщение от админа придет
	$pmsn_modul = 'close';
else
{
	$pmsn_modul = isset($_REQUEST['mdl']) ? trim($_REQUEST['mdl']) : 'new';
	
	if ($DBC_user['g_pm'] == 0 || $DBC_user['messages_enable'] == 0)
		if (!in_array($pmsn_modul, array('new','topic','close','closeq')))
			message($lang_common['No permission']);

	if ($pmsn_modul == 'new' && $DBC_user['messages_new'] == 0)
		$pmsn_modul = 'list';
}

// проверка модуля
if (!preg_match('/^[a-z]+$/', $pmsn_modul))
	message($lang_common['Bad request']);

if (!file_exists(DBC_ROOT.'engine/modules/pms_new/mdl/'.$pmsn_modul.'.php'))
	message(sprintf($lang_pmsn['No modul message'], $pmsn_modul));

if (function_exists('csrf_hash'))
	$pmsn_csrf_hash = csrf_hash();
else
	$pmsn_csrf_hash = '1';

// запросы по папкам
$pmsn_arr_list = array();
$pmsn_arr_new = array();
$pmsn_arr_save = array();

$sidamp = $sidvop = $siduser = '';

$sid = isset($_GET['sid']) ? intval($_GET['sid']) : 0;
if ($sid < 2)
	$sid = 0;

if ($sid)
{
	$result = $db->query('SELECT id, starter, to_user, starter_id, topic_st, topic_to  FROM '.$db->prefix.'pms_new_topics WHERE (starter_id = '.$DBC_user['id'].' AND topic_st != 2 AND to_id='.$sid.') OR (to_id = '.$DBC_user['id'].' AND topic_to != 2 AND starter_id='.$sid.') ORDER BY last_posted DESC') or error('Unable to fetch pms topics IDs', __FILE__, __LINE__, $db->error());
	if (!$db->num_rows($result))
		$sid = 0;
	else
	{
		$sidamp = '&amp;sid='.$sid;
		$sidvop = '?sid='.$sid;
	}
}
if ($sid == 0)
	$result = $db->query('SELECT id, starter, to_user, starter_id, topic_st, topic_to  FROM '.$db->prefix.'pms_new_topics WHERE (starter_id = '.$DBC_user['id'].' AND topic_st != 2) OR (to_id = '.$DBC_user['id'].' AND topic_to != 2) ORDER BY last_posted DESC') or error('Unable to fetch pms topics IDs', __FILE__, __LINE__, $db->error());

while ($ttmp = $db->fetch_assoc($result))
{
	if ($sid && empty($siduser))
	{
		if ($ttmp['starter_id'] == $sid)
			$siduser = DBC_htmlspecialchars($ttmp['starter']);
		else
			$siduser = DBC_htmlspecialchars($ttmp['to_user']);
	}
	
	if ($ttmp['starter_id'] == $DBC_user['id'])
		$ftmp = $ttmp['topic_st'];
	else
		$ftmp = $ttmp['topic_to'];

	if ($ftmp == 0)
		$pmsn_arr_list[] = $ttmp['id'];
	else if ($ftmp == 3)
		$pmsn_arr_save[] = $ttmp['id'];
	else if ($ftmp == 1)
	{
		$pmsn_arr_new[] = $ttmp['id'];
		$pmsn_arr_list[] = $ttmp['id'];
	}
}

$pmsn_kol_list = count($pmsn_arr_list);
$pmsn_kol_new = count($pmsn_arr_new);
$pmsn_kol_save = count($pmsn_arr_save);

// можно ли создать новый диалог
if ($DBC_user['g_pm'] == 0 || $DBC_user['messages_enable'] == 0 || ($DBC_user['g_pm_limit'] != 0 && $pmsn_kol_list >= $DBC_user['g_pm_limit'] && $pmsn_kol_save >= $DBC_user['g_pm_limit']))
  $pmsn_f_cnt = '';
else
  $pmsn_f_cnt = '<span><a href="pmsnew.php?mdl=post'.$sidamp.'">'.$lang_pmsn['New dialog'].'</a></span>';

// подключаем скрипт для бб-кодов - Visman
if (in_array($pmsn_modul, array('topic','edit','post')))
{
	if ($DBC_config['o_quickpost'] == '1' && $pmsn_modul == 'topic')
	{
		$apq  = 'var apq = {\'Must\' : \''.$lang_common['Must'].'\'';
		$apq .= ', \'Loading\' : \''.$lang_common['Loading'].'\'';
		$apq .= ', \'Flag\' : \'PM\'';
		$apq .= '}';
		$page_head['apq'] = '<script type="text/javascript">'."\n".'/* <![CDATA[ */'."\n".$apq."\n".'/* ]]> */'."\n".'</script>';
	}
	$page_head['bbcode'] = '<script type="text/javascript" src="engine/classes/js/post.js"></script>';
}

if (file_exists(DBC_ROOT.'templates/'.$DBC_user['style'].'/newpm.css'))
	$page_head['pmsnewstyle'] = '<link rel="stylesheet" type="text/css" href="templates/'.$DBC_user['style'].'/newpm.css" />';
else
	$page_head['pmsnewstyle'] = '<link rel="stylesheet" type="text/css" href="engine/skins/newpm.css" />';

$page_title = array(DBC_htmlspecialchars($DBC_config['o_board_title']), $lang_pmsn['PM'], $lang_pmsn[$pmsn_modul]);

include DBC_ROOT.'engine/modules/pms_new/mdl/'.$pmsn_modul.'.php';

if (!defined('DBC_PMS_LOADED'))
	message(sprintf($lang_pmsn['Modul failed message'], $pmsn_modul));

// Output the clearer div
?>
	<div class="clearer"></div>
</div>
<?php
$footer_style = 'index';
require DBC_ROOT.'engine/footer.php';
